<?php
require 'User.php';
require 'UserRepository.php';
require 'database.inc.php';
session_start();

require_once('smarty3/Smarty.class.php');
require_oncer('smarty3/SmartyValidate.class.php');
require_once('customSmartyValidator.php');
require 'addChatUser.php';


$smarty =& new Smarty();
$validator = new Validator($db);

if(empty($_POST)) {
    SmartyValidate::connect($smarty, true);
    SmartyValidate::register_object('validator', $validator);
    SmartyValidate::register_criteria('usernameAvaliable', 'validator->username_avaliable','default');
    SmartyValidate::register_criteria('emailAvaliable', 'validator->email_avaliable','default');
    SmartyValidate::register_validator('usernameExists', 'username1', 'usernameAvaliable');
    SmartyValidate::register_validator('usernameEmpty','username1','notEmpty');    
    SmartyValidate::register_validator('passwordLength','pass:4:-1','isLength');
    SmartyValidate::register_validator('passwordMatch','pass:pass2','isEqual');
    SmartyValidate::register_validator('nameEmpty','name','notEmpty');
    SmartyValidate::register_validator('surnameEmpty','surname','notEmpty');
    SmartyValidate::register_validator('emailIsEmail','email','isEmail');
    SmartyValidate::register_validator('emailExists', 'email', 'emailAvaliable');

   
    $_POST['username1']='';
    $_POST['email']='';
    $_POST['name']='';
    $_POST['surname']='';
    $smarty->assign('post', $_POST);
    $smarty->display('register.tpl');
} else {
    SmartyValidate::connect($smarty);
    SmartyValidate::register_object('validator', $validator);
    
    if(SmartyValidate::is_valid($_POST)) {
    
        SmartyValidate::disconnect();
        
        $user = new User(0,$_POST['username1'], sha1($_POST['pass']), $_POST['email'],
                $_POST['name'], $_POST['surname']);
        $users =  new UserRepository();
        $users->addUser($db, $user);
        addChatUser($_POST['username1'],$_POST['pass'],$_POST['email'],$_POST['name']);
        header('Location:index.php');        
    } else {
        // error, redraw the form
        $smarty->assign('post', $_POST);
        $smarty->display('register.tpl');
    }
}

